namespace Test.ConsoleProgram.Algorithm.Solution
{
    [TestDescription("算法: 0008. 字符串转换整数 (atoi)")]
    public class No0008_MyAtoi : AbsBaseTestItem
    {
        public override void OnTest()
        {
            Assert.TestExe(MyAtoi, "42", 42);
            Assert.TestExe(MyAtoi, "   -42", -42);
            Assert.TestExe(MyAtoi, "4193 with words", 4193);
            Assert.TestExe(MyAtoi, "words and 987", 0);
            Assert.TestExe(MyAtoi, "-91283472332", -2147483648);
            Assert.TestExe(MyAtoi, "3.14159", 3);
            Assert.TestExe(MyAtoi, "1", 1);
            Assert.TestExe(MyAtoi, "-", 0);
            Assert.TestExe(MyAtoi, "+1", 1);
            Assert.TestExe(MyAtoi, "+-2", 0);
        }

        public int MyAtoi(string str)
        {
            string input = (str ?? "").Trim();
            input = System.Text.RegularExpressions.Regex.Replace(input, @"^([\+\-]?[0-9]+).*", @"$1");
            if (int.TryParse(input, out int num))
                return num;
            if (!System.Text.RegularExpressions.Regex.IsMatch(input, @"^[\+\-]?[0-9]+$"))
                return 0;
            return input[0] == '-' ? input.Length > 1 ? int.MinValue : 0 : int.MaxValue;
        }
    }
}
